import {history, post, message, get, logout} from '@/utils/utils'
import {appId} from '@/config'

export const refreshToken = (cb) => {
  const headers = {
    isToken: 'false', Authorization: 'Basic YWd0OmFndA==', 'TENANT-ID': '1'
  }

  const userInfo = wx.getStorageSync('userInfo')

  if (!userInfo) return logout()

  const {refresh_token} = userInfo

  return post({
    api: `/auth/oauth/token?refresh_token=${refresh_token}&scope=server&grant_type=refresh_token`,
    headers,
    noTip: true,
    success: (data) => {
      wx.setStorageSync('userInfo', data)
      cb && cb(data)
    }
  })
}

const success = (data, cb) => {
  const {expires_in} = data
  setTimeout(() => {
    refreshToken(cb)
  }, (expires_in * 1000))
}

const login = {
  namespaced: true,
  state: {
    userInfo: {},
    isSelected: false
  },

  mutations: {
    toggleSelect (state) {
      state.isSelected = !state.isSelected
    },
    save(state, { field, payload }) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    tapSelect ({ commit }) {
      commit('toggleSelect')
    },

    login({ commit, dispatch, state: { isSelected } }, {data: {phoneNo, sms}}) {
      if (!phoneNo || !sms) return message.error('请先填写手机号和验证码')

      const headers = {
        isToken: 'false',
        Authorization: 'Basic YWd0OmFndA==',
        'TENANT-ID': 1
      }

      post({api: `/auth/mobile/token/sms?mobile=SMS@${phoneNo}&code=${sms}&grant_type=mobile`,
        headers,
        success: (data) => {
          success(data)
          wx.setStorageSync('userInfo', data)
          history.push('/pages/home/index')
        }})
    },

    getVerCode({ commit }, phoneNo) {
      get({api: `/agt/agentinfo/registerSendSms/${phoneNo}`,
        headers: {isToken: 'false', Authorization: 'Basic YWd0OmFndA=='},
        success: () => {
          message.success('发送成功')
        }})
    },

    async wxLogin({commit, dispatch, state: { isSelected }}, {noDirection, noTip, cb} = {}) {
      const headers = {
        isToken: 'false',
        Authorization: 'Basic YWd0OmFndA==',
        'TENANT-ID': 1
      }

      const auth_code = await dispatch('login', null, {root: true})

      post({
        api: `/auth/mobile/token/social?grant_type=mobil&mobile=MINI@${auth_code},${appId}`,
        headers,
        noLoading: noDirection,
        noTip,
        success: (data) => {
          if (!noDirection) {
            wx.setStorageSync('userInfo', data)
            success(data, () => commit('save', { field: 'userInfo', payload: data }))
            history.replace('/pages/home/index')
          }

          cb && cb(data)
        },
        fail: () => {
          cb && cb({access_token: undefined})
        }
      })
    }
  }
}

export default login
